using CodePen.Server.Language;
namespace CodePen.Web.Controllers;

/// <summary>
/// 
/// </summary>
[Authorize]
public partial class CategoryController : Controller
{
    /// <summary>
    /// 
    /// </summary>
    private readonly CategoryService _categoryService;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="CategoryService"></param> 
    public CategoryController(CategoryService CategoryService)
    {
        _categoryService = CategoryService; 
    }

    public IActionResult Index()
    {
        return View();
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("category/pages")]
    public async Task<RestfulResult<PageResult<PickCategory>>> GetPagesAsync()
    {
        using var sr = new StreamReader(Request.Body);
        string dataStr = await sr.ReadToEndAsync();
        if (Request.Body.CanSeek)
            Request.Body.Position = 0;
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new Exception(i18n.upload_data_required);
        CategoryPageParam? data = JsonConvert.DeserializeObject<CategoryPageParam>(dataStr);
        data ??= new CategoryPageParam { PageNo = 1, PageSize = 10 };

        var query = await _categoryService.GetPagesAsync(data);
        return query;
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous, HttpPost("category/list")]
    public async Task<RestfulResult<PageResult<PickCategory>>> GetlistAsync()
    {
        var restful = await _categoryService.GetlistAsync();
        return restful;
    }

    /// <summary>
    /// 增加
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork]
    [HttpPost("category/add")]
    public async Task<RestfulResult> AddAsync([FromBody] PickCategory data)
    {
        var restful = await _categoryService.AddAsync(data);
        return restful;
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("category/update")]
    public async Task<RestfulResult> UpdateAsync([FromBody] PickCategory data)
    {
        var restful = await _categoryService.UpdateAsync(data);
        return restful;
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete("category/delete")]
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        var restful = await _categoryService.DeleteAsync(data);
        return restful;
    }
}

